<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class InventoryRecord extends Model
{
    /**
     * 可批量赋值的属性
     */
    protected $fillable = [
        'material_id',
        'type',
        'quantity',
        'user_id',
        'remark'
    ];

    /**
     * 类型常量
     */
    const TYPE_IN = 1;  // 入库
    const TYPE_OUT = 2; // 出库

    /**
     * 获取关联的材料
     */
    public function material()
    {
        return $this->belongsTo(Material::class);
    }

    /**
     * 获取操作人
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取操作类型文本
     */
    public function getTypeTextAttribute()
    {
        return $this->type == 1 ? '入库' : '出库';
    }

    /**
     * 获取操作类型样式
     */
    public function getTypeClassAttribute()
    {
        return $this->type == 1 ? 'success' : 'warning';
    }

    /**
     * 处理出入库操作
     */
    public static function handleInventory($materialId, $type, $quantity, $operatorId, $remark = null)
    {
        $material = Material::findOrFail($materialId);
        
        // 检查出库数量是否超过库存
        if ($type == self::TYPE_OUT && $material->quantity < $quantity) {
            throw new \Exception('出库数量不能超过库存数量');
        }

        // 创建记录
        $record = self::create([
            'material_id' => $materialId,
            'type' => $type,
            'quantity' => $quantity,
            'operator_id' => $operatorId,
            'remark' => $remark
        ]);

        // 更新库存
        $material->quantity += ($type == self::TYPE_IN ? $quantity : -$quantity);
        $material->save();

        return $record;
    }
} 